<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            离线盘点
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;">
        <ul class="aui-list aui-form-list">
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">器具条码</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="选择/扫描器具条码" id="codeBar" value="" onclick="getIdSelector();" />
                    </div>
                    <div class="aui-btn aui-btn-primary" style="margin-right: 0.5rem;background-color: #03a9f4"
                        onclick="doSearch()">寻卡</div>
                </div>
            </li>

            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">器具数量</div>
                    <div class="aui-list-item-input">
                        <input disabled=true type="text" id="number" value="" onclick="getIdSelector();" />
                    </div>

                </div>
            </li>
        </ul>
        <div style="width:100%;margin-top:2%;"></div>
        <div class="aui-btn aui-btn-info" style="width:90%;margin-left:5%;" onclick="sqliteSave()">保存到本地</div>

        <div style="background-color:white; height: 100%;width: 100%;margin-top:2%;margin-bottom:50px;">
            <table class="table" style='width:100%;' id="table">
                <thead>
                    <tr
                        style="text-align: center;background-color: #DCE9F2;color: #467aa7;font-size: 12px;font-weight: bold;word-wrap:break-word;word-break:break-all;">
                        <td algin='center' width='80%'>器具条码</td>
                        <td algin='center' width='20%'></td>
                    </tr>
                </thead>
                <tbody id="tbodyHtml">
                </tbody>
            </table>
        </div>
    </div>

</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript">
    //光标所在id
    var idSelector = "";
    var sysid = ""; //盘点单据GID
    var arraylist = new Array();
    // 获取光标所在组件的id
    function getIdSelector() {
        var e = event || window.event;
        var el = e.srcElement || e.target;
        if (el.id == "billCode") {
            $("#billCode").select();
        } else if (el.id == "rsCode") {
            $("#rsCode").select();
        }
        idSelector = el.id;
        $("#" + el.id).select();
    }

    //3；PDA自带扫描回车事件
    $("#codeBar").on('keypress', function (e) { //#keyword为input文本框
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {
            //仓库编码
            if (sm != null && sm != "" && sm != undefined) {
                $("#codeBar").blur();

                var codeBarCells = document.querySelectorAll("td[name='codeBar']");
                var codeBarArray = [];
                // 遍历这些<td>元素并提取它们的文本值
                codeBarCells.forEach(function (cell) {
                    codeBarArray.push(cell.innerText.trim());
                });

                if (!codeBarArray.includes(sm)) {
                    var html = "";
                    html += "<tr style='text-align: center;color: black;font-size: 12px;background-color: #F5F5F5;'>";
                    html += "<td name='codeBar'>" + sm + "</td>";
                    html += "<td name='button'>" + "<div class='aui-btn aui-btn-info' onclick=\"deleteRow(this,'" + sm + "')\">删除</div> " + "</td>";
                    html += "</tr>";
                    $("#tbodyHtml").append(html);
                }
                $("#codeBar").val("");
                $("#codeBar").focus();
                //$api.html($api.byId("tbodyHtml"), html);
            }
        }
    });

    function deleteRow(button,ass) {

        $("#number").val($("#number").val() - 1);
        var row = button.parentNode.parentNode;
        // 获取表格的引用
        var table = document.getElementById("table").getElementsByTagName('tbody')[0];
        arraylist = arraylist.filter(item => item.ASCII !== ass);
        // 删除当前行
        table.removeChild(row);
    }

    //二维码扫描监听回车事件
    $("#rsCode").on('keypress', function (e) { //#keyword为input文本框
        var keycode = e.keyCode;
        var rsCode = $(this).val();
        //扫码方式
        var scan = $("input[name='scan']:checked").val();
        //盘点单号非空校验
        if (scan == "RFIDType") {
            api.toast({
                msg: '当前扫码方式为RFID扫码',
                duration: 3000
            });
            return;
        }
        if (keycode == '13') {

            //发货单
            $("#rsCode").val(rsCode);

            //查询表格数据
            saveQrcode();
        }
    });
    //返回按钮
    function closeWin() {
        api.closeWin({});
    }

    //调用RFID扫码api
    function getRfidData() {
        //操作状态
        var type = $("input[name='type']:checked").val();
        //扫码方式
        var scan = $("input[name='scan']:checked").val();

        if (scan == "QCodeType") {
            api.toast({
                msg: '当前扫码方式为二维码扫码',
                duration: 3000
            });
            return;
        }
        var moduleRfid = api.require('moduleRfid');
        if (type == 'OnLine') {
            moduleRfid.startActivityForResult({
                appParam: ""
            }, function (ret, err) {
                if (ret) {
                    saverrfid(ret);
                }
            });
        } else if (type == 'OffLine') {
            moduleRfid.startActivityForResult({
                appParam: ""
            }, function (ret, err) {
                if (ret) {
                    sqliteSave(ret);
                }
            });
        }

    }
    //离线盘点
    function sqliteSave(ret) {

        // var arr1 = ret.split("\n");
        // var arr = [];
        // for (var z = 0; z < arr1.length; z++) {
        //     arr[z] = arr1[z].split(":")[0];
        // }
        // //alert(arr)
        // var result = Array.from(new Set(arr))
        // // alert(result)
        // //盘点单号
        // var billCode = $("#billCode").val();
        // for (var i = 0; i < result.length; i++) {
        //     //RFID 16进制转换字符串
        //     result[i] = hexToString(result[i].substring(0, 14));
        // }
        // //alert(result)
        // if (billCode == "" || billCode == null || billCode == undefined) {
        //     api.toast({
        //         msg: '盘点单号不能为空',
        //         duration: 3000
        //     });
        //     return;
        // }
        var db = api.require('db');
        db.openDatabase({
            name: 'test'
        }, function (ret, err) {
            if (ret.status) {
                //console.log("1：数据库创建成功");
                //创建数据表
                db.executeSql({
                    name: 'test',
                    sql: 'CREATE TABLE if not exists AssetEncoding( qjCode varchar(255))'
                }, function (ret, err) {
                    if (ret.status) {

                        //console.log("2：数据库表AssetEncoding创建成功");

                        var codeBarCells = document.querySelectorAll("td[name='codeBar']");
                        // 遍历这些<td>元素并提取它们的文本值
                        codeBarCells.forEach(function (cell) {
                            //插入数据
                            db.executeSql({
                                name: 'test',
                                sql: " insert into AssetEncoding(qjCode) values('" + cell.innerText.trim() + "')"
                            }, function (ret, err) {
                                if (ret.status) {
                                    arraylist = new Array();
                                    api.hideProgress();
                                    api.toast({
                                        msg: "数据已存至本地数据库",
                                        duration: 3000
                                    });
                                    $api.html($api.byId("tbodyHtml"), "");
                                    $("#number").val("0");
                                    // console.log("3：数据库表数据插入成功");

                                }
                            });

                        });


                    } else {
                        alert(JSON.stringify(err));
                    }
                });
            } else {
                alert(JSON.stringify(err));
            }
        });
    }
    //查询本地数据库
    function sqliteGet() {
        var db = api.require('db');
        db.openDatabase({
            name: 'test'
        }, function (ret, err) {
            db.selectSql({
                name: 'test',
                sql: "REPLACE into Assetencoding(ZcCode, billCode) VALUES('6600123', 'ZC-20221111-0048')"
            }, function (ret, err) {
                if (ret.status) {
                    alert(JSON.stringify(ret));
                    console.log(JSON.stringify(ret));
                } else {
                    alert(JSON.stringify(err));
                }
            });

        });
    }

    //查询本地数据库
    function SQL() {
        var db = api.require('db');
        db.openDatabase({
            name: 'test'
        }, function (ret, err) {
            db.selectSql({
                name: 'test',
                sql: "SELECT count(ZcCode),billCode FROM AssetEncoding group by billCode"
                //sql: 'DELETE FROM AssetEncoding'
                //sql: "ALTER TABLE AssetEncoding ADD billCode VARCHAR(255) "
                //sql: "insert or replace into Assetencoding(ZcCode, billCode) values('6600123','ZC-20221111-0048')"
                //sql: "drop table if exists AssetEncoding"
            }, function (ret, err) {
                if (ret.status) {
                    alert(JSON.stringify(ret));
                    console.log(JSON.stringify(ret));
                } else {
                    alert(JSON.stringify(err));
                }
            });

        });
    }

    //16进制转换字符串
    function hexToString(str) {
        var val = "";
        var len = str.length / 2;
        for (var i = 0; i < len; i++) {
            val += String.fromCharCode(parseInt(str.substr(i * 2, 2), 16));
        }
        return val;
    }
    //跳转页面
    function goPage() {
        var name = "";
        //操作状态
        var type = $("input[name='type']:checked").val();
        //扫码方式
        var scan = $("input[name='scan']:checked").val();
        //盘点单号
        var billCode = $("#billCode").val();
        if (billCode == "" || billCode == null || billCode == undefined) {
            api.toast({
                msg: '盘点单号不能为空',
                duration: 3000
            });
            return;
        }

        if (scan == "QCodeType") {
            name = "rsInventoryQRcode";
            api.openWin({
                name: name,
                url: name + '.html',
                pageParam: {
                    name: "qcmChkBillCreate",
                    billCode: billCode,
                    type: type,
                }
            });
        } else if (scan == "RFIDType") {
            var moduleRfid = api.require('moduleRfid');
            if (type == "OnLine") {
                moduleRfid.startActivityForResult({
                    appParam: ""
                }, function (ret, err) {
                    if (ret) {
                        saverrfid(ret);
                    }
                });
            } else if (type == "OffLine") {
                moduleRfid.startActivityForResult({
                    appParam: ""
                }, function (ret, err) {
                    if (ret) {
                        sqliteSave(ret);
                    }
                });
            }
        }

    }

    //调用RFID扫码api
    function doSearch() {
        var moduleUhfRfid = api.require('moduleUhfRfidEpc');
        moduleUhfRfid.startActivityForResult({
            appParam: ""
        }, function (ret, err) {
            if (ret) {
                //alert(ret);
                var array = eval(ret);
                arraylist = arraylist.concat(array);

                // 或者使用filter和findIndex  
                var list = arraylist.filter((only, index, self) =>
                    index === self.findIndex((t) => (
                        t.ASCII === only.ASCII
                    ))
                );

                $("#number").val(list.length);

                var html = "";

                if (list != null && list != undefined && list.length > 0) {
                    document.getElementById('tbodyHtml').innerHTML = '';
                    //divStr += "<tr style='text-align:center;color:#0099FF;border-collapse: collapse'><th style='border: 1px solid white;border-collapse: collapsel;width:60%'>器具条码</th><th style='border: 1px solid white;border-collapse: collapse;width:40%'>删除条码</th></tr>"
                    for (var i = 0; i < list.length; i++) {
                        //divStr += "<tr style='text-align:center;color:#0099FF;border-collapse: collapse'><td id= 'tm' style='border: 1px solid white;border-collapse: collapse;width:60%''>" + list[i].ASCII + "</td>" + "<td style='border: 1px solid white;border-collapse: collapse;width:40%'><button class='deleteRowBtn' style = 'border:none:outline:none;background-color:red'>删除</button></td></tr>"

                        html += "<tr style='text-align: center;color: black;font-size: 12px;background-color: #F5F5F5;'>";
                        html += "<td name='codeBar'>" + list[i].ASCII + "</td>";
                        html += "<td name='button'>" + "<div class='aui-btn aui-btn-info' onclick=\"deleteRow(this,'" + list[i].ASCII + "')\">删除</div> " + "</td>";
                       html += "</tr>";
                    }
                    // $("$table").append(divStr);
                    $("#tbodyHtml").append(html);
                }

                $("#codeBar").val("");
                $("#codeBar").focus();
            } else {
                //alert(err);
            }
        });
    }

</script>

</html>